//
//  SearchViewController.m
//  Everest
//
//  Created by 李其昌 on 14/12/24.
//  Copyright (c) 2014年 ThreeL. All rights reserved.
//

#import "SearchViewController.h"

// 搜索页面
#import "SearchViewController.h"
#import "NetHandler.h"
#import "Album.h"
#import "UIImageView+WebCache.h"
#import "UIColor+AddColor.h"
#import "DownloadCell.h"
#import "MusicSearch.h"
#import "AlbumTableViewCell.h"
#import "AlbumViewController.h"
#import "PlayViewController.h"
#import "HotPresent.h"
#import "UIColor+AddColor.h"
#define NORMAL @"normalReuse"
#define SOUNDS @"SoundsReuse"
#define ALBUM @"albumReuse"
#define kCellWidth [UIApplication sharedApplication].keyWindow.bounds.size.width

@interface SearchViewController () <UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

//@property (nonatomic, retain)UISearchBar *searchBar;
//@property(nonatomic, retain) NSString *scope;
//@property(nonatomic ,retain) UITableView *tableView;
//@property(nonatomic, retain) UISegmentedControl *seg;

// 表
@property (nonatomic, retain) UITableView *searchTableView;

// 数据数组
@property (nonatomic, retain) NSMutableArray *arr;
// 声音数组
@property (nonatomic, retain) NSMutableArray *soundArr;
// 专辑数组
@property (nonatomic, retain) NSMutableArray *AlbumArr;
// 搜索框
@property (nonatomic, retain) UISearchBar *searchBar;
// 标记显示哪一种cell
@property (nonatomic, assign) NSInteger flag;
// segment
@property (nonatomic, retain) UISegmentedControl *segment;
// 当前请求的是第几页
@property (nonatomic, retain) NSString *page;
// 一共找到多少条记录
@property (nonatomic, assign) NSNumber *numFound;
// 现在是哪个cell
@property (nonatomic, retain) NSString *mark;

@property (nonatomic, retain) NSString *searBarStr;


// 最后更新时间
@property(nonatomic, retain)UILabel *lastUptrackAtLabel;
// 播放次数
@property(nonatomic, retain)UILabel *playsCountsLabel;


@end

@implementation SearchViewController


#pragma mark 初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.mark = @"normal";
        self.flag = 2;
        self.page = @"1";
        self.arr = [NSMutableArray array];
        self.soundArr = [NSMutableArray array];
        self.AlbumArr = [NSMutableArray array];
    }
    
    return self;
}

#pragma mark 释放
- (void)dealloc
{
    [_searchTableView release];
    [_searchBar release];
    [super dealloc];
}

#pragma mark 获取网络数据

- (void)handleData
{
    NSString *str = @"http://mobile.ximalaya.com/m/hot_search_keys?device=IPhone";
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        [self.arr addObjectsFromArray:[sourceDic objectForKey:@"keys"]];
        
        [self.searchTableView reloadData];
    }];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self handleData];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = YES;
//    self.navigationController.navigationBar.translucent = YES;
    
    self.navigationItem.hidesBackButton = YES;
#pragma mark 设置搜索栏
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen]       .bounds.size.width, 30)];
    view.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:view];
    //设置搜索栏  固定在导航栏下边
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 0, self.view.bounds.size.width - 30, 30)];
    _searchBar.placeholder=@"搜索声音,专辑";
    _searchBar.delegate = self;
    _searchBar.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.searchBar];
    //是否进行文字纠错  YES. NO;
    _searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    //单词首字母是否大写  None不大写   Words大写
    _searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _searchBar.searchBarStyle = UISearchBarStyleMinimal;
    
    //让Cancel按钮显示出来
    self.searchBar.showsCancelButton = YES;
    //让搜索栏成为第一响应者
    [self.searchBar becomeFirstResponder];
    
    [_searchBar release];
    
    [view addSubview:self.searchBar];
    self.navigationItem.titleView = view;
    
    self.segment = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"专辑",@"声音", nil]];
    self.segment.selectedSegmentIndex = 0;
    self.segment.alpha = 1;
    self.segment.backgroundColor = [UIColor whiteColor];
    self.segment.tintColor = [UIColor kuGouColor];
    self.segment.frame = CGRectMake(0, 5, self.view.frame.size.width, 30);
    [self.segment addTarget:self action:@selector(changeSegment:) forControlEvents:UIControlEventValueChanged];
    [_segment release];
    
    
#pragma mark 设置tableView
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.bounds.origin.x, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    
    
    self.searchTableView.dataSource = self;
    self.searchTableView.delegate = self;
    self.searchTableView.sectionHeaderHeight = 40;

    [self.view addSubview:self.searchTableView];
    
    [self.searchTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NORMAL];
    [self.searchTableView registerClass:[AlbumTableViewCell class] forCellReuseIdentifier:SOUNDS];
//
    [self.searchTableView registerClass:[DownloadCell class] forCellReuseIdentifier:ALBUM];
    
    // Do any additional setup after loading the view.
  
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //让Cancel按钮显示出来
    self.searchBar.showsCancelButton = YES;
    [searchBar resignFirstResponder];
}


#pragma mark searchBar的协议方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    searchBar.showsCancelButton = YES;
    self.searBarStr = searchText;
        
        if (self.flag == 1) {
            
            [self.arr removeAllObjects];
            [self.soundArr removeAllObjects];
            [self getSoundsInfor:searchText];
            
        } else if (self.flag == 0) {
            
            [self.arr removeAllObjects];
            [self.AlbumArr removeAllObjects];
            [self getAlbumInfor:searchText];
        } else if (self.flag == 2) {
            
            [self.arr removeAllObjects];
            [self.AlbumArr removeAllObjects];
            [self getAlbumInfor:searchText];
            self.flag = 0;
        }
    
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    //显示离开按钮
    
    
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
    
}


#pragma mark tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.flag == 2) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NORMAL];
        cell.textLabel.text = [self.arr objectAtIndex:indexPath.row];
        return cell;
    } else if (self.flag == 1) {
        
        AlbumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SOUNDS];
        cell.music = [self.arr objectAtIndex:indexPath.row];
        return cell;
    } else if (self.flag == 0){

        DownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:ALBUM];
        cell.music = [self.arr objectAtIndex:indexPath.row];
        return cell;
    }
    
    return nil;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [NSString stringWithFormat:@"section:%ld", section];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }
    // Create header view and add label as a subview
    UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, tableView.bounds.size.height)] autorelease];
    [sectionView setBackgroundColor:[UIColor whiteColor]];
    // sectionView.userInteractionEnabled = YES;
    [sectionView addSubview:self.segment];
    
    return sectionView;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.flag == 2) {
        
        return (self.view.bounds.size.height - 64 - 40) / self.arr.count;
        
    } else if (self.flag == 1) {
        
        return 100;
    } else {
        
        
        NSString *title = [[self.arr objectAtIndex:indexPath.row] title];
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
        
        CGRect rect = [title boundingRectWithSize:CGSizeMake(self.view.bounds.size.width / 2, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        CGFloat imageHeight = (kCellWidth / 7) + 10;
        
        CGFloat titleHeight = rect.size.height + (self.view.bounds.size.height / 667 * 35);
        
        CGFloat lastHeight = imageHeight > titleHeight ? imageHeight : titleHeight;
        return lastHeight;
    }
}

// cell的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.searchBar resignFirstResponder];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([self.mark isEqualToString:@"normal"] && self.searBarStr.length == 0) {
        
        if (self.segment.selectedSegmentIndex == 1) {
            self.mark = nil;
            NSString *str = [self.arr objectAtIndex:indexPath.row];
            self.searBarStr = str;
            [self.arr removeAllObjects];
            [self.soundArr removeAllObjects];
            [self.searchTableView reloadData];
            [self getSoundsInfor:str];
            
        } else if (self.segment.selectedSegmentIndex == 0) {
            self.mark = nil;
            NSString *str = [self.arr objectAtIndex:indexPath.row];
            self.searBarStr = str;
            [self.arr removeAllObjects];
            [self.AlbumArr removeAllObjects];
            [self.searchTableView reloadData];
            self.flag = 0;
            [self getAlbumInfor:str];
        }
        
    } else if (self.segment.selectedSegmentIndex == 0) {

        AlbumViewController *albumDetailsVC = [[AlbumViewController alloc] init];
        albumDetailsVC.classifyDetail = [self.arr objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:albumDetailsVC animated:YES];
        [albumDetailsVC release];
        
    } else if (self.segment.selectedSegmentIndex == 1){
        
        PlayViewController *playVC = [PlayViewController defaultPlayVC];
        HotPresent *hotplay = [[HotPresent alloc] init];
        MusicSearch *music = [self.arr objectAtIndex:indexPath.row];
        
        hotplay.playUrl64 = music.play_path_64;
        hotplay.albumId = music.album_id;
        hotplay.coverLarge = music.cover_path;
        
        playVC.hotPlay = hotplay;
        
        [self presentViewController:playVC animated:YES completion:^{
            
            
        }];
        
    }
    
}

#pragma mark segment的方法

- (void)changeSegment:(UISegmentedControl *)seg
{
    [self.searchBar resignFirstResponder];
    if (seg.selectedSegmentIndex == 0) {
        self.flag = 0;
        if (self.searchBar.text.length != 0) {
            [self.arr removeAllObjects];
            [self.searchTableView reloadData];
            [self.AlbumArr removeAllObjects];
            [self getAlbumInfor:self.searchBar.text];
        } else {
            
            [self.arr removeAllObjects];
            [self.searchTableView reloadData];
            [self.AlbumArr removeAllObjects];
            [self getAlbumInfor:self.searBarStr];
            
        }
    } else if (seg.selectedSegmentIndex == 1) {
        self.flag = 1;
        if (self.searchBar.text.length != 0) {
            
            [self.arr removeAllObjects];
            [self.searchTableView reloadData];
            [self.soundArr removeAllObjects];
            [self getSoundsInfor:self.searchBar.text];
            
        } else {

//            NSLog(@"%@", self.searchBar.text);
            [self.arr removeAllObjects];
            [self.searchTableView reloadData];
            [self.soundArr removeAllObjects];
            [self getSoundsInfor:self.searchBar.text];
            
        }
        
    }
    
}


#pragma mark 获得声音信息

- (void)getSoundsInfor:(NSString *)str
{
    NSString *strPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/s/mobile/search?device=iPhone&condition=%@&page=%@&per_page=20&scope=voice", str, self.page];
//    NSLog(@"%@", strPath);
    [NetHandler getDataWithUrl:strPath completion:^(NSData *data) {
        
        NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSDictionary *responseDic = [sourceDic objectForKey:@"response"];
        
        self.numFound = [responseDic objectForKey:@"numFound"];
        
        NSArray *docsArr = [responseDic objectForKey:@"docs"];
        
        for (NSDictionary *dic in docsArr) {
            
            MusicSearch *albumDetailsOflist = [[MusicSearch alloc] initWithDictionary:dic];
            [self.soundArr addObject:albumDetailsOflist];
            [albumDetailsOflist release];
        }
        [self.arr removeAllObjects];
        [self.arr addObjectsFromArray:self.soundArr];
        [self.searchTableView reloadData];
    }];
    
    
}

#pragma mark 获得专辑信息

- (void)getAlbumInfor:(NSString *)str
{
    NSString *strPath = [NSString stringWithFormat:@"http://mobile.ximalaya.com/s/mobile/search?device=iPhone&condition=%@&page=%@&per_page=20&scope=album", str, self.page];
//    NSLog(@"%@", strPath);
    [NetHandler getDataWithUrl:strPath completion:^(NSData *data) {
        
        NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSDictionary *responseDic = [sourceDic objectForKey:@"response"];
        
        self.numFound = [responseDic objectForKey:@"numFound"];
        
        NSArray *docsArr = [responseDic objectForKey:@"docs"];
        
        for (NSDictionary *dic in docsArr) {
            
            MusicSearch *albumOflist = [[MusicSearch alloc] initWithDictionary:dic];
            [self.AlbumArr addObject:albumOflist];
            [albumOflist release];
        }
        [self.arr removeAllObjects];
        [self.arr addObjectsFromArray:self.AlbumArr];
        
        
        
        [self.searchTableView reloadData];
    }];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
